package com.jianyitech.asr.service;

import com.alibaba.fastjson.JSON;
import com.jianyitech.asr.kafka.producer.ProducerService;
import com.jianyitech.asr.mapper.AsrRuleMapper;
import com.jianyitech.asr.dtos.AsrRule;
import com.jianyitech.asr.utils.Constant;
import com.jianyitech.asr.utils.DateUtil;
import com.jianyitech.asr.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service
public class AsrRuleService {


    private static final Logger logger = LoggerFactory.getLogger(AsrRuleService.class);

    @Autowired
    AsrRuleMapper ruleMapper;

    @Autowired
    ProducerService producerService;

    @Autowired
    StringRedisTemplate redisTemplate;


    public List<AsrRule> queryByTenantId(String tenantId){
        return ruleMapper.queryByTenantId(tenantId);
    }


    public void noticeClient(String tenantId){
        logger.info("[NoticeClient]: tenantId -> {}",tenantId);
        String topic = Constant.TOPICS.TENANT_ASR_RULE_PREFIX+tenantId;
        List<AsrRule> rules = this.queryByTenantId(tenantId);
        if(null!=rules && !rules.isEmpty()){
            Map<Object,Object> map = redisTemplate.opsForHash().entries(Constant.CACHE.TENANT_HEARTBEAT_CACHE_PREFIX+tenantId);
            if(null!=map && !map.isEmpty()){
                long timestamp = DateUtil.getTimestamp();
                for(Map.Entry<Object,Object> entry : map.entrySet()) {
                    String ip = StringUtil.trim(entry.getKey());
                    String val = StringUtil.trim(entry.getValue());
                    long value = Long.parseLong(StringUtil.trim(val,"0"));
                    long diff = timestamp - value;
                    if(diff<600) {
                        producerService.sendMessage(topic+"_"+ip, JSON.toJSONString(rules));
                    }else{
                        redisTemplate.opsForHash().delete(Constant.CACHE.TENANT_HEARTBEAT_CACHE_PREFIX+tenantId,ip);
                    }
                }
            }

        }

    }














}
